# -*- coding: utf-8 -*-
#!/usr/bin/env python
import datetime
import time
import logging
import os
from markdown import markdown

import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from tornado.options import define, options

from session import WebSession
from api import User, UserDetail, Log, UserSpace

#import uimodules
#from utils import random_string, random_digits

define("port", default=8888, help="run on the given port", type=int)

class BaseHandler(tornado.web.RequestHandler):
    '''Base Request Handler with auth and seesion'''
    def get_current_user(self):
        return self.session()["user"]

    def session(self):
        if hasattr(self, '_session'):
            return self._session
        session_id = self.get_secure_cookie('SESSID')
        if session_id:
            logging.debug('SESSID: %s' % session_id)
            self._session = WebSession(session_id)
        else:
            self._session = WebSession()
            self.set_secure_cookie('SESSID', self._session.id)
        return self._session


class LoginHandler(BaseHandler):
    def get(self):
        next = self.get_argument("next", '/')
        errno = self.get_argument("errno", 0)
        self.render('login.html', next=next, errno=str(errno))

    def post(self):
        nickname = self.get_argument("nickname", '')
        password = self.get_argument("password", '')
        next = self.get_argument("next", '/')
        if User.valid(nickname, password):
            u = User.get_by_nickname(nickname)
            email = u["email"]
            self.session()['user'] = {'nickname': nickname, 'email':email}
            self.redirect(next)
        else:
            errno = 2
            self.redirect("/auth/login?errno=%d" % errno)


class RegisterHandler(BaseHandler):
    def get(self):
        next = self.get_argument("next", '/')
        info = self.get_argument("info", '')
        self.render('register.html', next=next, info=info)

    def post(self):
        email = self.get_argument("email", '')
        password = self.get_argument("password", '')
        nickname = self.get_argument("nickname", '/')
        next = self.get_argument("next", '/')

        result, info = User.register(email, password, nickname)

        if result:
            u = User.get_by_email(email)
            UserSpace.add(email, 'default')
            self.session()['user'] = {'nickname': nickname, 'email':email}
            self.redirect(next)
        else:
            self.redirect("/auth/register?next=%s&info=%s" % (next, info))


class LogoutHandler(BaseHandler):
    def get(self):
        self.clear_cookie("SESSID")
        self.redirect("/")


class MainHandler(BaseHandler):
    def get(self):
        u = self.get_current_user()
        if u:
            myspace = UserSpace.get_by_full(u['email'], 'default')
            logs = Log.get_by_email(u['email'], myspace['_id'])
            spaces = UserSpace.get_spaces(u['email'])
            logtype = ['idea', 'resource', 'progress']
        
            self.render('index.html', logs=logs, logtype=logtype,
                spaces=spaces, space_now='default', markdown=markdown)
        else:
            self.render('index_guest.html')


    @tornado.web.authenticated
    def post(self):
        ts = int(time.time())
        logtype = self.get_argument('logtype')
        content = self.get_argument('logcontent')
        email = self.get_current_user()['email']
        space_now = self.get_argument('space_now')
        space = UserSpace.get_by_full(email, space_now)
        space_id = space['_id']
        tags = [logtype]
        Log.add_log(ts, email, space_id, tags, content)
        self.redirect('/')


class SpaceHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self, space):
        u = self.get_current_user()
        if u:
            myspace = UserSpace.get_by_full(u['email'], space)
            logs = Log.get_by_email(u['email'], myspace['_id'])
            spaces = UserSpace.get_spaces(u['email'])
        else:
            logs = []
            spaces = []
        logtype = ['idea', 'resource', 'progress']
        
        self.render('index.html', logs=logs, logtype=logtype,
            spaces=spaces, space_now=space, markdown=markdown)

    @tornado.web.authenticated
    def post(self, space):
        ts = int(time.time())
        logtype = self.get_argument('logtype')
        content = self.get_argument('logcontent')
        email = self.get_current_user()['email']
        space_now = self.get_argument('space_now')
        space = UserSpace.get_by_full(email, space_now)
        space_id = space['_id']
        tags = [logtype]
        Log.add_log(ts, email, space_id, tags, content)
        self.redirect('/')


class NewSpaceHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        self.render('newspace.html')

    @tornado.web.authenticated
    def post(self):
        name = self.get_argument("name", '')
        email = self.get_current_user()['email']
        UserSpace.add(email, name)
        self.redirect("/space/"+name)


class AccountHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        email = self.get_current_user().get('email')
        user = User.get_by_email(email)
        userdetail = UserDetail.get_by_email(email)
        self.render('account_basic.html', user=user, userdetail=userdetail)

    @tornado.web.authenticated
    def post(self):
        email = self.get_current_user().get('email')
        nickname = self.get_current_user().get('nickname')
        userdetail = UserDetail.get_by_email(email)
        if userdetail is None: userdetail = {"email":email}
        arguments = ['intro', 'gender', 'birthday', 'hometown',
            'city', 'job']
        for a in arguments:
            userdetail[a] = self.get_argument(a, '')
        UserDetail.update(userdetail)
        self.redirect('/profile/'+nickname)


class ProfileHandler(BaseHandler):
    def get(self, nickname):
        user = User.get_by_nickname(nickname)
        userdetail = {}
        if user:
            userdetail = UserDetail.get_by_email(user['email'])
        self.render(
            'profile.html', user=user, userdetail=userdetail)


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", MainHandler),
            (r"/newspace", NewSpaceHandler),
            (r"/space/(.+)", SpaceHandler),
            (r"/account/basic/", AccountHandler),
            (r"/profile/(.+)", ProfileHandler),
            (r"/auth/register", RegisterHandler),
            (r"/auth/login", LoginHandler),
            (r"/auth/logout", LogoutHandler),
        ]
        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            cookie_secret='random_123456',
            login_url='/auth/login',
            autoescape="xhtml_escape",
#            ui_modules=uimodules,
        )
        tornado.web.Application.__init__(self, handlers, **settings)


def main():
    tornado.options.parse_command_line()
    application = Application()
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()


if __name__ == "__main__":
    main()
